<template>
  <div class="data-comparator-container">
    <div class="data-comparator">
      <div class="card">
        <div class="card-header">
          <h2>数据比较工具</h2>
        </div>

        <div class="input-section">
          <div class="input-group">
            <h3>第一列数据</h3>
            <!--            <textarea-->
            <!--              v-model="firstColumn"-->
            <!--              class="data-input"-->
            <!--              placeholder="请粘贴第一列数据（支持Excel复制）"-->
            <!--              @paste="handlePaste($event, 'first')"-->
            <!--              @change="handleTextChange('first')"-->
            <!--            ></textarea>-->
            <textarea
              v-model="firstColumn"
              class="data-input"
              placeholder="请粘贴第一列数据（支持Excel复制）"
              @input="handleTextChange('first')"
            ></textarea>
            <div class="input-info">行数: {{ firstLength }}</div>
          </div>

          <div class="input-group">
            <h3>第二列数据</h3>
            <textarea
              v-model="secondColumn"
              class="data-input"
              placeholder="请粘贴第二列数据（支持Excel复制）"
              @input="handleTextChange('second')"
            ></textarea>
            <div class="input-info">行数: {{ secondLength }}</div>
          </div>
        </div>

        <div class="options-section">
          <div class="option-group">
            <label>小数位数比较：</label>
            <select v-model="decimalPlaces">
              <option value="-1">不忽略小数</option>
              <option value="0">忽略小数</option>
              <option value="1">保留1位小数</option>
              <option value="2">保留2位小数</option>
              <option value="3">保留3位小数</option>
              <option value="4">保留4位小数</option>
            </select>
          </div>
        </div>

        <div class="button-section">
          <button class="compare-btn" @click="handleLineByLineCompare" :disabled="!canCompare">
            逐行比较
          </button>
          <button class="compare-btn" @click="handleSortCompare" :disabled="!canCompare">
            排序比较
          </button>
        </div>

        <div class="result-section" v-if="showResults">
          <div v-if="comparisonType === 'line'">
            <h3>逐行比较结果</h3>
            <div class="result-content">
              <div v-for="(diff, index) in lineDifferences" :key="index" class="diff-item">
                第 {{ diff.line }} 行: {{ diff.first }} ≠ {{ diff.second }}
              </div>
            </div>
            <div class="csv-preview">
              <pre>{{ formatLineCSV(lineDifferences) }}</pre>
            </div>
            <button
              class="download-btn"
              @click="
                downloadCSV(
                  lineDifferences.map((d) => `${d.line},${d.first},${d.second}`),
                  'line_differences.csv',
                )
              "
            >
              下载CSV
            </button>
          </div>

          <div v-else-if="comparisonType === 'sort'">
            <h3>排序比较结果</h3>
            <div class="result-tabs">
              <button :class="['tab-btn', { active: activeTab === 1 }]" @click="activeTab = 1">
                仅在第一列中存在 ({{ type1Differences.length }})
              </button>
              <button :class="['tab-btn', { active: activeTab === 2 }]" @click="activeTab = 2">
                仅在第二列中存在 ({{ type2Differences.length }})
              </button>
              <button :class="['tab-btn', { active: activeTab === 3 }]" @click="activeTab = 3">
                共同存在但数量不同 ({{ commonDifferences.length }})
              </button>
            </div>

            <div class="result-content">
              <div v-if="activeTab === 1">
                <div class="csv-preview">
                  <pre>数据,出现次数<br>{{ formatCountCSV(type1Differences) }}</pre>
                </div>
                <button
                  class="download-btn"
                  @click="
                    downloadCSV(
                      type1Differences.map((d) => `${d.value},${d.count}`),
                      'type1_differences.csv',
                    )
                  "
                >
                  下载CSV
                </button>
              </div>
              <div v-else-if="activeTab === 2">
                <div class="csv-preview">
                  <pre>数据,出现次数<br>{{ formatCountCSV(type2Differences) }}</pre>
                </div>
                <button
                  class="download-btn"
                  @click="
                    downloadCSV(
                      type2Differences.map((d) => `${d.value},${d.count}`),
                      'type2_differences.csv',
                    )
                  "
                >
                  下载CSV
                </button>
              </div>
              <div v-else>
                <div class="csv-preview">
                  <pre>
数据,第一列出现次数,第二列出现次数<br>{{ formatCommonCSV(commonDifferences) }}</pre>
                </div>
                <button
                  class="download-btn"
                  @click="
                    downloadCSV(
                      commonDifferences.map((d) => `${d.value},${d.firstCount},${d.secondCount}`),
                      'common_differences.csv',
                    )
                  "
                >
                  下载CSV
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const firstColumn = ref('')
const secondColumn = ref('')
const comparisonType = ref<'line' | 'sort' | null>(null)
const activeTab = ref(1)
const showResults = ref(false)

const firstLength = computed(() => firstColumnLines.value.length)
const secondLength = computed(() => secondColumnLines.value.length)

const firstColumnLines = ref<string[]>([])
const secondColumnLines = ref<string[]>([])

const canCompare = computed(() => {
  return firstColumnLines.value.length > 0 && secondColumnLines.value.length > 0
})

const lineDifferences = ref<Array<{ line: number; first: string; second: string }>>([])
const type1Differences = ref<Array<{ value: string; count: number }>>([])
const type2Differences = ref<Array<{ value: string; count: number }>>([])
const commonDifferences = ref<Array<{ value: string; firstCount: number; secondCount: number }>>([])

const decimalPlaces = ref(-1) // -1表示不忽略小数

const formatNumber = (value: string): string => {
  if (decimalPlaces.value === -1) return value
  if (decimalPlaces.value === 0) return value.split('.')[0]

  const num = parseFloat(value)
  if (isNaN(num)) return value

  return num.toFixed(decimalPlaces.value)
}

const handleTextChange = (type: 'first' | 'second') => {
  const text = type === 'first' ? firstColumn.value : secondColumn.value
  const lines = text.split('\n').map((line) => {
    const columns = line.split('\t')
    return formatNumber(columns[0].trim())
  })

  if (type === 'first') {
    firstColumnLines.value = lines
  } else {
    secondColumnLines.value = lines
  }
}

// const handlePaste = (event: ClipboardEvent, type: 'first' | 'second') => {
//   const pastedText = event.clipboardData?.getData('text')
//   if (!pastedText) return
//
//   // 处理Excel复制的数据（可能包含制表符）
//   const lines = pastedText.split('\n').map((line) => {
//     const columns = line.split('\t')
//     return columns[0].trim()
//   })
//
//   if (type === 'first') {
//     // firstColumn.value = lines.join('\n')
//     firstColumnLines.value = lines
//   } else {
//     // secondColumn.value = lines.join('\n')
//     secondColumnLines.value = lines
//   }
// }

const handleLineByLineCompare = () => {
  comparisonType.value = 'line'
  showResults.value = true
  lineDifferences.value = []

  const maxLines = Math.max(firstColumnLines.value.length, secondColumnLines.value.length)
  for (let i = 0; i < maxLines; i++) {
    const first = firstColumnLines.value[i] || ''
    const second = secondColumnLines.value[i] || ''
    if (first !== second) {
      lineDifferences.value.push({
        line: i + 1,
        first,
        second,
      })
    }
  }
}

const handleSortCompare = () => {
  comparisonType.value = 'sort'
  showResults.value = true
  activeTab.value = 1

  // 统计第一列数据出现次数
  const firstMap = new Map<string, number>()
  firstColumnLines.value.forEach((item) => {
    firstMap.set(item, (firstMap.get(item) || 0) + 1)
  })

  // 统计第二列数据出现次数
  const secondMap = new Map<string, number>()
  secondColumnLines.value.forEach((item) => {
    secondMap.set(item, (secondMap.get(item) || 0) + 1)
  })

  // 找出仅在第一列中存在的数据
  type1Differences.value = Array.from(firstMap.entries())
    .filter(([key]) => !secondMap.has(key))
    .map(([value, count]) => ({ value, count }))

  // 找出仅在第二列中存在的数据
  type2Differences.value = Array.from(secondMap.entries())
    .filter(([key]) => !firstMap.has(key))
    .map(([value, count]) => ({ value, count }))

  // 找出共同存在但数量不同的数据
  commonDifferences.value = Array.from(firstMap.entries())
    .filter(([key]) => secondMap.has(key))
    .map(([value, firstCount]) => ({
      value,
      firstCount,
      secondCount: secondMap.get(value) || 0,
    }))
    .filter((item) => item.firstCount !== item.secondCount)
}

const formatCSV = (data: string[]) => {
  return data.join('\n')
}

const formatLineCSV = (differences: Array<{ line: number; first: string; second: string }>) => {
  return (
    '行号,第一列数据,第二列数据\n' +
    differences.map((d) => `${d.line},${d.first},${d.second}`).join('\n')
  )
}

const formatCountCSV = (data: Array<{ value: string; count: number }>) => {
  return data.map((d) => `${d.value},${d.count}`).join('\n')
}

const formatCommonCSV = (
  data: Array<{ value: string; firstCount: number; secondCount: number }>,
) => {
  return data.map((d) => `${d.value},${d.firstCount},${d.secondCount}`).join('\n')
}

const downloadCSV = (data: string[], filename: string) => {
  const blob = new Blob([data.join('\n')], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
</script>

<style scoped>
.data-comparator-container {
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  background-color: #f5f7f8;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.data-comparator {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  padding: 24px;
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 24px;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #2d3748;
  font-weight: 600;
}

.input-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-group h3 {
  margin: 0;
  font-size: 16px;
  color: #4a5568;
}

.data-input {
  width: 100%;
  height: 200px;
  padding: 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  resize: vertical;
  font-family: monospace;
}

.input-info {
  font-size: 14px;
  color: #718096;
}

.options-section {
  margin-bottom: 20px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.option-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.option-group label {
  font-size: 14px;
  color: #4a5568;
}

.option-group select {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  font-size: 14px;
  color: #2d3748;
  cursor: pointer;
}

.option-group select:focus {
  outline: none;
  border-color: #4f46e5;
}

.button-section {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.compare-btn {
  padding: 12px 24px;
  background: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.compare-btn:hover:not(:disabled) {
  background: #4338ca;
  transform: translateY(-1px);
}

.compare-btn:disabled {
  background: #cbd5e0;
  cursor: not-allowed;
}

.result-section {
  margin-top: 24px;
}

.result-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #2d3748;
}

.result-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.tab-btn {
  padding: 8px 16px;
  background: #edf2f7;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #4a5568;
  transition: all 0.3s ease;
}

.tab-btn.active {
  background: #4f46e5;
  color: white;
}

.result-content {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  min-height: 200px;
}

.diff-item {
  padding: 8px;
  border-bottom: 1px solid #e2e8f0;
  font-family: monospace;
}

.csv-preview {
  background: white;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.csv-preview pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: monospace;
}

.download-btn {
  padding: 8px 16px;
  background: #4f46e5;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.download-btn:hover {
  background: #4338ca;
  transform: translateY(-1px);
}
</style>
